<?php

namespace App\Orchid\Screens\Page;

use App\Models\Page;
use Illuminate\Http\Request;
use Orchid\Screen\Screen;
use Orchid\Screen\Fields\Input;
use Orchid\Screen\Fields\Quill;
use Orchid\Screen\Fields\Select;
use Orchid\Screen\Actions\Button;
use Orchid\Support\Facades\Toast;
use Orchid\Support\Facades\Layout;
use Illuminate\Support\Str;

class PageEditScreen extends Screen
{
    /**
     * @var Page
     */
    public $page;

    /**
     * Fetch data to be displayed on the screen.
     *
     * @param Page $page
     *
     * @return array
     */
    public function query(Page $page): iterable
    {
        return [
            'page' => $page,
        ];
    }

    /**
     * The name of the screen displayed in the header.
     */
    public function name(): ?string
    {
        return $this->page->exists ? '编辑页面' : '新建页面';
    }

    /**
     * Display header description.
     */
    public function description(): ?string
    {
        return $this->page->exists ? '编辑现有页面内容' : '创建新的静态页面';
    }

    /**
     * The screen's action buttons.
     *
     * @return \Orchid\Screen\Action[]
     */
    public function commandBar(): iterable
    {
        return [
            Button::make('保存')
                ->icon('check')
                ->method('save'),

            Button::make('删除')
                ->icon('trash')
                ->method('remove')
                ->canSee($this->page->exists)
                ->confirm('确定要删除这个页面吗？'),
        ];
    }

    /**
     * The screen's layout elements.
     *
     * @return \Orchid\Screen\Layout[]
     */
    public function layout(): iterable
    {
        return [
            Layout::tabs([
                '主要内容' => Layout::rows([
                    Input::make('page.title')
                        ->title('页面标题')
                        ->placeholder('输入页面标题')
                        ->required()
                        ->help('页面的显示标题'),

                    Input::make('page.slug')
                        ->title('Slug')
                        ->placeholder('自动生成或手动输入')
                        ->help('URL友好的标识符，留空将自动生成'),

                    Quill::make('page.content')
                        ->title('页面内容')
                        ->placeholder('输入页面内容')
                        ->required()
                        ->help('页面的主要内容'),
                ]),
                
                '设置' => Layout::rows([
                    Select::make('page.status')
                        ->title('状态')
                        ->options([
                            'draft' => '草稿',
                            'published' => '已发布',
                        ])
                        ->value('draft')
                        ->help('页面的发布状态'),

                    Input::make('page.template')
                        ->title('模板')
                        ->placeholder('default')
                        ->value('default')
                        ->help('页面使用的模板名称'),
                ]),
            ]),
        ];
    }

    /**
     * Save page
     *
     * @param Request $request
     * @param Page $page
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function save(Request $request, Page $page)
    {
        $request->validate([
            'page.title' => 'required|string|max:255',
            'page.slug' => 'nullable|string|max:255|unique:pages,slug,' . $page->id,
            'page.content' => 'required|string',
            'page.status' => 'required|in:draft,published',
            'page.template' => 'nullable|string|max:255',
        ]);

        $data = $request->get('page');
        
        // 自动生成slug
        if (empty($data['slug'])) {
            $data['slug'] = Str::slug($data['title']);
        }
        
        // 确保slug唯一
        $data['slug'] = $this->ensureUniqueSlug($data['slug'], $page->id);
        
        // 设置作者
        if (!$page->exists) {
            $data['user_id'] = auth()->id();
        }
        
        // 设置默认模板
        if (empty($data['template'])) {
            $data['template'] = 'default';
        }

        $page->fill($data)->save();

        Toast::info('页面已保存');

        return redirect()->route('platform.pages');
    }

    /**
     * Remove page
     *
     * @param Page $page
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function remove(Page $page)
    {
        $page->delete();

        Toast::info('页面已删除');

        return redirect()->route('platform.pages');
    }
    
    /**
     * Ensure slug is unique
     *
     * @param string $slug
     * @param int|null $excludeId
     * @return string
     */
    private function ensureUniqueSlug(string $slug, ?int $excludeId = null): string
    {
        $originalSlug = $slug;
        $counter = 1;
        
        while (Page::where('slug', $slug)
            ->when($excludeId, fn($query) => $query->where('id', '!=', $excludeId))
            ->exists()) {
            $slug = $originalSlug . '-' . $counter;
            $counter++;
        }
        
        return $slug;
    }
}